package com.xunwulian.base.util;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.*;

/**
 * 字串工具
 */
public class StringUtil {

    /**
     * @param paramMap 参数map
     * @return 生成的xml字串
     */
    public static String mapToXml(Map<String, String> paramMap) {
        Document document = DocumentHelper.createDocument();
        Element xml = document.addElement("xml");
        for (String key : paramMap.keySet()) {
            Element param = xml.addElement(key);
            param.setText(paramMap.get(key));
        }
        return document.asXML();
    }

    /**
     * UUID生成唯一标识，长度为1~1024
     *
     * @param length 要生成的标识的长度
     * @return
     */
    public static String createIdentity(int length) {
        if (length < 1 || length > 1024) {
            return null;
        }

        StringBuilder identity = new StringBuilder();
        int pnum = length / 32;
        int snum = length % 32;
        for (int i = 0; i < pnum; i++) {
            identity.append(UUID.randomUUID().toString().replace("-", ""));
        }

        identity.append(UUID.randomUUID().toString().replace("-", "").substring(0, snum));

        return identity.toString();
    }

    /**
     * 按照Ascii排序
     *
     * @param keys 要排序的集合
     * @return
     */
    public static Collection<String> orderByAscii(Collection<String> keys) {
        List<String> keys2 = new ArrayList(keys);
        keys2.sort(new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                // 按照正序排
                char c1 = o1.charAt(0);
                char c2 = o2.charAt(0);
                if (c1 < c2) {
                    return -1;
                }
                if (c1 > c2) {
                    return 1;
                }
                return 0;
            }
        });

        return keys2;
    }
}
